<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Adm_Role extends Controller_Base_Backend {

	public function action_index() {
		$this->view->body->content = Smarty_View::factory("auth/adm/role.tpl");
		$role = new Model_Role($this->request->param('id'));
		$this->view->body->content->role = $role;
		$this->response->body($this->view);
	}

	public function action_list() {
		$this->view->body->content = Smarty_View::factory("auth/adm/list_role.tpl");
		$report = new Report(Model_Role::get_report());
		if (Model_User::logged_in("admin")) {
			$report->bind("id", __("id"));
		} else {
			$report->hide("id");
		}
		$report->bind("name", __("Name"), array("Report_Pandrade", "format_name"));
		$report->bind("description", __("Description"));
		$report->bind("actions", __("Actions"), array("Controller_Adm_Role", "format_actions"));
		$this->view->body->content->report = $report->parse();
		$this->response->body($this->view);
	}

	public function action_remove() {
		try {
			$role = Model_Role::factory($this->request->param('id'));
			$role->remove();
			Request::current()->redirect("adm/role/list/");
		} catch (Exception $e) {
			$errors = array("_external" => array("user"=>$e->getMessage()));
			$this->response->body(Json_View::factory(array("content" => $errors)));
		}
	}

	public function action_save() {
		try {
			$role = Model_Role::factory($_POST['role_id']);
			$role->set_name($_POST['role_name']);
			$role->set_description($_POST['role_description']);
			$role->save();
			Request::current()->redirect("adm/role/list/");
		} catch (Validation_Exception $e) {
			$this->response->body(Json_View::factory(array("content" => $e->errors())));
		} catch (Exception $e) {
			$errors = array("email" => $e->getMessage());
			$this->response->body(Json_View::factory(array("content" => $errors)));
		}
	}

	public static function format_actions($value) {
		$edit = "<a href='".url::base()."adm/role/index/$value'>";
		$edit.= "	<img src='".url::base()."modules/pandrade/static/images/report/edit.png' title='".__("Edit")."' alt='".__("Edit")."'>";
		$edit.= "</a>";
		$remove = "<a href='#' onclick=\"ajaxRemove('".url::base()."adm/role/remove/$value','".__("Do you really want to remove?")."')\">";
		$remove.= "	<img src='".url::base()."modules/pandrade/static/images/report/remove.png' title='".__('Remove')."' alt='".__('Remove')."'>";
		$remove.= "</a>";
		return $edit.$remove;
	}

} // End Role